<template>
  <div class="upload-container">
    <!-- 文件选择按钮 -->
    <el-upload
      action=""
      :auto-upload="false"
      :on-change="handleFileChange"
      :show-file-list="false"
      multiple
    >
      <el-button type="primary">选择文件</el-button>
    </el-upload>


    <!-- 弹窗：上传进度 -->
    <el-dialog title="文件上传中" :visible.sync="uploading" width="400px" :close-on-click-modal="false" :show-close="false">
      <el-progress :percentage="progress" :status="progress === 100 ? 'success' : 'active'"></el-progress>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fileList: [], // 存储选中的文件
      uploading: false, // 是否正在上传（控制弹窗）
      progress: 0 // 上传进度
    };
  },
  methods: {
    // 选择文件
    handleFileChange(file) {
      this.fileList.push(file.raw); // 只存储文件原始对象
      this.uploadFiles();
    },

    // 上传文件
    async uploadFiles() {
      if (this.fileList.length === 0) return;

      this.uploading = true; // 显示弹窗
      this.progress = 0; // 重置进度

      const formData = new FormData();
      this.fileList.forEach(file => {
        formData.append("files[]", file); // 多文件上传
      });

      try {
        // 模拟上传 (假设上传到 /upload)
        await this.fakeUpload(formData);
      } catch (error) {
        console.error("上传失败", error);
      }
    },

    // 模拟上传 (你可以替换为真实 API 请求)
    fakeUpload(formData) {
      return new Promise(resolve => {
        let progressInterval = setInterval(() => {
          if (this.progress >= 100) {
            this.closeDialog();
            clearInterval(progressInterval);
            resolve();
          } else {
            this.progress += 10;
          }
        }, 300);
      });
    },

    // 关闭弹窗
    closeDialog() {
      this.uploading = false;
      this.fileList = []; // 清空文件列表
    }
  }
};
</script>

<style scoped>
.upload-container {
  text-align: center;
}
</style>
